<template>
  <div class="mengli-set">
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title :title="!isEdit?'添加改名记录':'编辑改名记录'" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="configForm"
          :rules="rules"
          :model="queryData"
          label-position="right"
          label-width="90px"
          class="setting-form">
          <el-form-item label="账号名称" prop="name">
            <el-input
              v-model="queryData.name"
              :maxlength="100"
              style="font-size: 13px;width:240px;"
              type="text"
              size="small"
              placeholder="请输入账号名称"/>
          </el-form-item>
          <el-form-item label="改名日期" prop="date">
            <el-date-picker
              v-model="queryData.date"
              :clearable="false"
              :editable="false"
              style="font-size: 13px;width:240px;"
              type="date"
              value-format="timestamp"
              format="yyyy/MM/dd"
              size="small"
              class="order-time"/>
          </el-form-item>
        </el-form>
        <div class="btn-container" style="text-align: center;">
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
          <el-button :loading="btnLoading" type="primary" size="small" @click="handleOk">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="tableShow"
      :before-close="costTableClose"
      :append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="medium-common-dialog-size padding-justify"
    >
      <div class="flex" style="margin-bottom:10px;">
        <Title title="改名记录"/>
        <PlainCreateBtn v-if="hasRouteAuth('medium:changeName:create')" @click="addItem">添加</PlainCreateBtn>
      </div>
      <el-table
        v-loading="listloading"
        v-if="listData.items && listData.items.length"
        :data="listData.items"
        :max-height="tableHeight"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <el-table-column align="left" label="账号">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.name && scope.row.name.length > 20" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.name }}</div>
              <div class="ellipsisOne">{{ scope.row.name }}</div>
            </el-tooltip>
            <div v-else class="ellipsisOne">{{ scope.row.name || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="改名日期">
          <template slot-scope="scope">
            <span v-if="scope.row.date">{{ scope.row.date/1000 | standardFormat('YYYY/MM/DD') }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间">
          <template slot-scope="scope">
            <span v-if="scope.row.createdTime">{{ scope.row.createdTime/1000 | standardFormat('YYYY/MM/DD') }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建人">
          <template slot-scope="scope">
            <span>{{ scope.row.creator || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isAdmin || hasRouteAuth('medium:changeName:edit') || hasRouteAuth('medium:changeName:delete')" align="left" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="(isAdmin || hasRouteAuth('medium:changeName:edit'))" type="text" @click="editItem(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
            <el-button v-if="(isAdmin || hasRouteAuth('medium:changeName:delete'))" type="text" @click="deleteItem(scope.row)"><span style="font-size:14px;">删除</span></el-button>
          </template>
        </el-table-column>
      </el-table>
      <empty-placeholder v-else is-border mode="table" style="margin-top: 24px"/>
      <el-row v-if="listData.items && listData.items.length" type="flex" justify="end">
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="listData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { standardFormat } from '@/filters/date';
import ElMessage from '@/utils/message';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';

// 组件
import Title from '@/components/Title';
// api
import { getAccountNameChangeList, createAccountNameChangeList, editAccountNameChangeList, deleteAccountNameChangeList } from '@/api/resource';
// image
import setting from '@/assets/setting.png';
export default {
  name: 'ResourceNameConfig',
  components: {
    Title,
    EmptyPlaceholder
  },
  filters: {
    standardFormat
  },
  props: {
    tableVisible: {
      type: Boolean,
      default: false
    },
    activeMediumId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      setting,
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请输入账号名称' }],
        date: [{ required: true, trigger: 'blur', message: '请选择改名日期' }]
      },
      queryData: {
        name: '',
        date: new Date(new Date().toLocaleDateString()).getTime() // 0点
      },
      page: 1,
      perPage: 20,
      listloading: false,
      listData: {
        items: []
      },
      isEdit: false,
      dialogVisible: false,
      tableShow: false,
      btnLoading: false,
      tableHeight: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  watch: {
    tableVisible: {
      handler(newV) {
        newV && this.toOpenTable();
      },
      immediate: true
    }
  },
  created() {
    // this.getData();
  },
  methods: {
    hasRouteAuth,
    getData(reset) {
      if (reset) this.page = 1;
      const { page, perPage } = this;
      const params = {
        page,
        perPage,
        mediumId: this.activeMediumId
      };
      this.listloading = true;
      getAccountNameChangeList(params).then(res => {
        this.listloading = false;
        if (res.code === 200) {
          this.listData = res.data;
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listloading = false;
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.queryData = {
        name: '',
        date: new Date(new Date().toLocaleDateString()).getTime()
      };
    },
    editItem(item) {
      if (this.$refs.configForm) this.$refs.configForm.clearValidate(); // 清空校验
      this.queryData.name = item.name;
      this.queryData.date = new Date(new Date(item.date).toLocaleDateString()).getTime();
      this.queryData.id = item.id;
      this.isEdit = true;
      this.dialogVisible = true;
    },
    addItem() {
      this.isEdit = false;
      this.dialogVisible = true;
      if (this.$refs.configForm) this.$refs.configForm.clearValidate();// 清空校验
    },
    handleOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      paramsObj.mediumId = this.activeMediumId;
      this.$refs.configForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.edit(paramsObj);
          } else {
            this.add(paramsObj);
          }
        } else {
          return false;
        }
      });
    },
    edit(params) {
      this.btnLoading = true;
      editAccountNameChangeList(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.getData();
          ElMessage.success('编辑成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      createAccountNameChangeList(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.getData(true);
          ElMessage.success('添加成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    // 表格展示
    toOpenTable() {
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 3) / 5;
      this.tableShow = true;
      this.getData();
    },
    costTableClose() {
      this.tableShow = false;
      this.$emit('handleClose');
    },
    deleteItem(item) {
      this.$confirm('是否确定删除该改名记录？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteAccountNameChangeList(item.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getData();
          } else {
            this.$message.closeAll();
            this.$message.error(res.message);
          }
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {});
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData();
    }
  }
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
.padding-justify {
  &::v-deep {
    .el-dialog__body {
      padding-top: 19px !important;
    }
  }
}
</style>
